package com.yootk.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;

@WebFilter("/pages/front/*")
public class InvalidateFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String userid = (String) request.getSession().getAttribute("userid"); // 获取用户ID
        if (userid != null) {   // 用户未登录
            Map<String, Boolean> map = (Map<String, Boolean>) request.getServletContext().getAttribute("online");
            if (map.containsKey(userid)) {  // 指定用户信息存在
                if (map.get(userid) == true) {  // 用户已剔除
                    request.getSession().invalidate(); // Session强制清除
                    request.setAttribute("error", "您的账户已被系统强制下线，为了您的安全，请重新登录！");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);// 跳转
                } else {// 用户
                    chain.doFilter(request, response); // 转发请求目标
                }
            }
        } else {    // 用户未登录
            request.setAttribute("error", "您还未登录，请先登录！");   // 错误信息
            request.getRequestDispatcher("/login.jsp").forward(request, response);  // 跳转
        }
    }
}
